package com.cloud.storage.service.impl;

import com.cloud.storage.service.FileUploadService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author lhj
 * @Date 2024/9/1 14:40
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${minio.bucket}")
    private String bucketName;

    @Autowired
    private MinioClient minioClient;

   

    @Override
    public String uploadFile(MultipartFile file) {
        try {
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isBlank(originalFilename)) {
                throw new RuntimeException("文件名为空");
            }
            //获取文件后缀
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String originName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String uuid = UUID.randomUUID().toString().substring(0, 16);
            String fileName = String.format("%s-%s-%s.%s", timestamp, uuid, originName, fileSuffix);
            log.info("解析到的文件名");
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                log.warn("桶不存在：{}，创建桶", bucketName);
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            minioClient.putObject(putObjectArgs);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String previewFile(String fileName) {
        GetPresignedObjectUrlArgs presignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(fileName)
                //设置过期时间
                .expiry(1, TimeUnit.HOURS)
                .build();
        try {
            return  minioClient.getPresignedObjectUrl(presignedObjectUrlArgs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
